package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "认证中心")
@RestController
@RequestMapping("/api/user/passport")
public class PassPortApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     * @param userInfo
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        UserInfo userInfoLogin = userService.login(userInfo);
        if (null != userInfoLogin) {
            String token = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String nickName = userInfoLogin.getNickName();
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("token", token);
            resultMap.put("nickName", nickName);

            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;

            JSONObject userJson = new JSONObject();
            userJson.put("userId", userInfoLogin.getId());
            userJson.put("ip", IpUtil.getIpAddress(request));
            String userValue = userJson.toJSONString();
            redisTemplate.opsForValue().set(userKey, userValue, RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(resultMap);
        } else {
            return Result.<Map<String, String>>fail().message("用户名或密码不正确");
        }
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(userKey);
        return Result.ok();
    }
}
